﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HgReleaseNotesGen
{
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;

    [DebuggerDisplay("{VersionNumber}:{ChangesetId.RepositoryId}")]
    class Release
    {
        public string VersionNumber { get; private set; }

        public ChangesetId ChangesetId { get; private set; }

        public List<string> Notes { get; private set; }
 
        public Release(string versionNumber, string remoteChangesetId)
        {
            this.VersionNumber = versionNumber;
            this.ChangesetId = new ChangesetId(string.Empty, remoteChangesetId);
            this.Notes = new List<string>();
        }

        public static List<Release> LoadReleasesFromStream(StreamReader stream)
        {
            var releases = new List<Release>();

            while (!stream.EndOfStream)
            {
                var release = Release.LoadReleaseFromStream(stream);
                if (release != null)
                {
                    releases.Add(release);
                }
            }

            return releases;
        }

        public static Release LoadReleaseFromStream(StreamReader stream)
        {
            Release release = null;

            while (!stream.EndOfStream)
            {
                var peek = stream.Peek();

                if (release == null)
                {
                    var line = stream.ReadLine();

                    if (line == null)
                    {
                        break;
                    }

                    line = line.Trim();

                    // Comments are ignored
                    if (line != string.Empty && !line.StartsWith("#"))
                    {
                        var lineStart = line.SubstringBefore(':').Trim();
                        var lineEnd = line.SubstringAfter(':').Trim();
                        if (char.IsDigit(lineStart, 0))
                        {
                            release = new Release(lineStart, lineEnd);
                        }
                    }
                }
                else
                {
                    if (peek >= 48 && peek <= 57)
                    {
                        break;
                    }

                    var line = stream.ReadLine();

                    if (line == null)
                    {
                        break;
                    }

                    line = line.Trim();

                    // Comments are ignored
                    if (line != string.Empty && !line.StartsWith("#"))
                    {
                        release.Notes.Add(line);
                    }
                }
            }


            return stream.EndOfStream ? null : release;
        }
  
    }
}
